<?php

# http://projects:8081/cdapp-2kt-api/api/get_seat_status.php

include_once '_portal.php';
forbidden_acc();

$seat = isset($_GET['seat']) ? $_GET['seat'] : '*';

$status = [];
if (!$seat || $seat == '*') {
  $status = get_all_seat_status();
} else {
  $status = get_specified_seat_status($seat);
}
output($status);

# clear disposed planning

function clear_planning() {
  $sql_arr = [
    "UPDATE `2kt_seat_status` SET `planningSectorCodes`= null WHERE `sectorCodes` = `planningSectorCodes`",
    "UPDATE `2kt_seat_status` SET `planningFrequency`= null WHERE `frequency` = `planningFrequency`",
  ];
  exec_sql_array($sql_arr);
}

# get all seat

function get_all_seat_status() {
  clear_planning();
  $sql = "SELECT * FROM `2kt_seat_status`";
  $data = exec_sql($sql);
  // add version
  $version = get_version();
  $available = get_available();
  if ($data) {
    $data = query_parse($data);
    return ['success' => true, 'content' => $data, 'version' => $version, 'available' => $available];
  } else {
    return ['success' => false, 'content' => $data, 'version' => $version, 'available' => $available];
  }
}

# get specific seat
# eg: seat=TM01,TM02,TM03...

function get_specified_seat_status($seat) {
  clear_planning();
  $seatName = implode("','", explode(',', $seat));
  $sql = "SELECT * FROM `2kt_seat_status` WHERE `seatName` IN ('$seatName')";
  $data = exec_sql($sql);
  // add version
  $version = get_version();
  $available = get_available();
  if ($data) {
    $data = query_parse($data);
    return ['success' => true, 'content' => $data, 'version' => $version, 'available' => $available];
  } else {
    return ['success' => false, 'content' => $data, 'version' => $version, 'available' => $available];
  }
}

function get_version() {
  $refresh_info = get_variable('SEAT_STATUS_TMA_RECIVE');
  if (!$refresh_info) {
    return -1;
  } else {
    return $refresh_info;
  }
}

function get_available() {
  if (get_variable('STOP_ALL_NETWORK') === 1) {
    return false;
  }
  if (get_variable('STOP_ATCOS') === 1) {
    return false;
  }
  return true;
}
